package com.shxc.smarttrade.old.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapter.RedPackAdapter;
import com.shxc.smarttrade.old.bean.RedPack;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.CommonDialog;
import com.shxc.smarttrade.old.myview.RecycleViewTwoDivider;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/8/12.
 */

public class RedPackActivity extends BaseActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_wait_get)
    TextView tvWaitGet;
    @BindView(R.id.tv_have_get)
    TextView tvHaveGet;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    LinearLayoutManager manager;
    RedPackAdapter adapter;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    RedPack redPack = (RedPack) msg.obj;
                    if (redPack.getErr_code().equals("0")) {
                        List<RedPack.DataBean.RedBean> redBeanList = redPack.getData().getRed();
                        if (redBeanList.size() > 0) {
                            adapter.setDatas(redBeanList);
                            tvWaitGet.setText(getChangeText("$ " + redPack.getData().getUCompletAmt()));
                            tvHaveGet.setText(getChangeText("$ " + redPack.getData().getCompletAmt()));
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_red_pack);
        initView();
        showShortDialog();
        initData();
        initListener();

    }

    private void initListener() {
        adapter.setOnMyClickListener(new RedPackAdapter.ItemClickListener() {
            @Override
            public void setOnClickListener(RedPack.DataBean.RedBean rb) {
                showShortDialog();
                getRedPack(rb.getId());

            }
        });
    }

    private void initData() {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", SpUtils.getInt(this, "userId", 0) + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.RED_PACK_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gson = new Gson();
                    RedPack redPack = gson.fromJson(response, RedPack.class);
                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = redPack;
                    handler.sendMessage(msg);
                }
                dismissShortDialog();
            }
        });
    }

    private void initView() {
        tvCenter.setText("我的红包");
        manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new RecycleViewTwoDivider(this, LinearLayout.VERTICAL, 20, getResources().getColor(R.color.all_background)));
        recyclerView.setAdapter(adapter = new RedPackAdapter(this));
    }

    @OnClick({R.id.rl_left, R.id.tv_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.tv_record:
                startActivity(new Intent(this, RedPackRecordActivity.class));
                break;
        }
    }

    private SpannableString getChangeText(String money) {
        SpannableString str = new SpannableString(money);
        RelativeSizeSpan span = new RelativeSizeSpan((float) 1.5);
        str.setSpan(span, 1, money.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return str;
    }

    private void getRedPack(int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", SpUtils.getInt(this, "userId", 0) + "");
        map.put("id", id + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.GET_RED_PACK, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsob = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "领取失败";
                    if (!jsob.get("err_code").isJsonNull())
                        errCode = jsob.get("err_code").getAsString();
                    if (!jsob.get("err_msg").isJsonNull())
                        errMsg = jsob.get("err_msg").getAsString();
                    if (errCode.equals("0"))
                        showAlertDialog("领取成功！红包现金将在1-2个工作日内存入您的交易账户。");
                    else
                        showToast(errMsg);
                }
                dismissShortDialog();

            }
        });
    }

    private void showAlertDialog(String msg) {

        CommonDialog commonDialog = new CommonDialog(this, R.style.customDialogStyle);
        commonDialog.setCanceledOnTouchOutside(true);
        commonDialog.setBaseText("提示", msg, "取消", "确定");
        commonDialog.setYesCLickRunAble(new Runnable() {
            @Override
            public void run() {
                showShortDialog();
                initData();
            }
        });
        commonDialog.show();
    }
}
